<?php

namespace App\Model\FBA;

use App\Model\WMS\Order\Ext;
use App\Model\WMS\Order\Core;
use App\Model\WMS\Order\Base;

class InboundShipment extends \Illuminate\Database\Eloquent\Model
{


//    use \jdavidbakr\ReplaceableModel\ReplaceableModel;


    const NAME = 'FBA入库单';

    protected $table = 'fba_inbound_shipment';

    public $incrementing = false;

    public $primaryKey = 'ShipmentId';

    protected $fillable = [
        'ShipmentId',
        'ShipmentName',
	    'ShipFromAddress',
	    'ShipToAddress',
	    'DestinationFulfillmentCenterId',
	    'LabelPrepType',
        'ShipmentStatus',
        'AreCasesRequired',

        'type',
        'step',
		'warehouse_from',
		'warehouse_to',

        'wms_order_id',
        'ec_id',
		'status',

        'created_at',
        'updated_at',
    ];

    protected $casts = [
        'ShipToAddress' => 'array',
        'ShipFromAddress' => 'array',
        'AreCasesRequired' => 'boolean',
    ];


//    use \Peak\Plugin\PropertyTranslater\Core;


    protected static $translation = [
        'status' => [
//            -2 => '已取消',
            -1 => 'CartonContent 上传失败',
	        0 => '未同步',
	        1 => '上传CartonContent',
        ],
        'type' => [
            Base\PurchaseIn::TYPE => Base\PurchaseIn::NAME,
            Base\TransferIn::TYPE => Base\TransferIn::NAME,
        ],
        'step' => [
            0 => '已取消',
	        1 => '计划中',
	        2 => '待提交',
	        3 => '物流&费用',
	        4 => '已发货',
//	        5 => '异常',
	        9 => '已完成',
        ],
        'type_of_label' => \App\Services\MWS\Request\FbaInboundShipment::PAGE_TYPE_OF_LABEL,
    ];



    protected static function boot ()
    {
        parent::boot();

        /*static::saving(function ($model) {
            $model->ShipmentId || $model->ShipmentId='SD'.date('ymd').'-'. \Peak\Plugin\Str::random(3, 1);
            $model->ShipmentName || $model->ShipmentName=$model->ShipmentId;
        });*/
    }


    ### 属性方法


    /**
     * 状态判断·Shipment或其明细是否可编辑
     * @param bool $item true 判断明细是否可编辑， false判断Shipment自身是否可编辑
     * @return true|null
     */
    public function canEdit ($item=false)
    {
        if ($this->status) {
            return self::debug('当前状态为“'.$this->translateProperty('status').'”，无法编辑。');
        }

        return $item
            ? ($this->step==1 ?: self::debug('当前流程为“'.$this->translateProperty('step').'”，不可修改明细。'))
            : ($this->step<3 ?: self::debug('当前流程为“'.$this->translateProperty('step').'”，不可编辑。'));
    }


    /**
     * 状态判断·是否可Confirm提交
     * @return bool
     */
    public function canConfirm ()
    {
        return $this->status ? self::debug('当前状态为“'.$this->translateProperty('status').'”，无法提交。') : true;
    }



    const ATTACHMENT_DIR = 'fba/inboud-shipment/';

    /**
     * 获取Model对应的附件文件名
     * @param null $name 文件名，如为null则默认使用Model的主键值作为文件名
     * @param string $ext 文件后缀名
     * @param string $dir 文件夹，默认为空则直接存放于根目录
     * @return string
     */
    public function getAttachmentFilename ($name=null, $ext='.xls', $dir='')
    {
        $name = $name ?: $this->{$this->primaryKey};
        $dir = $dir ? self::ATTACHMENT_DIR.$dir.'/' : self::ATTACHMENT_DIR;
        return $dir.$name.$ext;
    }

    /**
     * 生成MWS SDK
     * @param string $marketplace US,GB 默认null
     */
    public function sdk ($marketplace=null)
    {
        return sdkMws($this->ec_id)->fbaInboundShipment($marketplace);
    }




    ### Model交互


    /**
     * 转化成 Shipment Header格式（非Plan）
     * @return array
     */
    public function toMws ():array
    {
        return [
            'ShipmentName' => $this->ShipmentName,
            'ShipFromAddress' => (array)$this->ShipFromAddress,
            'DestinationFulfillmentCenterId' => $this->DestinationFulfillmentCenterId,
            'LabelPrepPreference' => $this->LabelPrepType,
            'AreCasesRequired' => (boolean)$this->AreCasesRequired,
            'ShipmentStatus' => @$this->ShipmentStatus ?: 'WORKING',
//                'IntendedBoxContentsSource' => @$this->IntendedBoxContentsSource ?: 'FEED',
        ];
    }



    public function toWMSOrder(): Core
    {
        return new Core([
            'type'=>$this->type,
            'warehouse_id'=>$this->warehouse_id,
            'area_id'=>0,
        ]);
    }

/*
    public function canWmsOrder(): bool
    {
        return true;
    }


    public function toWMSOrderStep ():int
    {
        return 0;
    }*/


    ######### relationship #########



    public function warehouseFrom ()
    {
        return $this->belongsTo(\App\Model\WMS\Warehouse::class, 'warehouse_from', 'id');
    }


    public function warehouseTo ()
    {
        return $this->belongsTo(\App\Model\WMS\Warehouse::class, 'warehouse_to', 'id');
    }



    public function item()
    {
        return $this->hasMany(\App\Model\FBA\InboundShipmentItem::class, 'ShipmentId', 'ShipmentId');
    }

    public function cartonFeed ()
    {
        return $this->morphOne(\App\Repository\ModelExt::class, 'ext', 'model', 'id', 'id')->where('type', 0);
    }


    public function palletExcel ()
    {
        return $this->morphOne(\App\Repository\ModelExt::class, 'ext', 'model', 'id', 'id')->where('type', 1);
    }



}
